package ChatRoom;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class TalkServerReceiveHelper extends Thread {

    private SocketMode socketMode = null;
    private TalkServerReceiveHelperListener listener = null;

    public TalkServerReceiveHelper(SocketMode socketMode) {
        this.socketMode = socketMode;
    }

    public void addTalkServerReceiveHelperListener(TalkServerReceiveHelperListener listener) {
        this.listener = listener;
    }

    @Override
    public void run() {
        InputStream inputStream = null;
        try {

            while (true) {
                // 获取当前的套接字对象
                Socket socket = socketMode.getSocket();
                inputStream = socket.getInputStream();
                // 读取客户端发送过来的信息
                byte[] buf = new byte[1024];
                int len = inputStream.read(buf);

                if (len == -1) {
                    // 客户端关闭了连接
                    break;
                }

                String str = new String(buf, 0, len);

                if (str.equals("bye")) {
                    if (listener != null) {
                        listener.handleClientClose(socketMode);
                    }
                    break;
                }

                if (listener != null) {
                    TCPServerFrame.SM=socketMode;
                    listener.updateTalkMessage(socketMode.getClientName() + ": " + str);
                    listener.broadcastMessage(socketMode, str);  // 广播消息给其他客户端
                }

                try {
                    Thread.sleep(100); // 稍作休息避免过度占用CPU
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static class TalkServerReceiveHelperListenerImpl implements TalkServerReceiveHelperListener {

        @Override
        public void handleClientClose(SocketMode socketMode) {
            System.out.println("Client " + socketMode.getClientName() + " has closed the connection.");
            SocketMode.removeClient(socketMode);
        }

        @Override
        public void updateTalkMessage(String message) {
            System.out.println("New message: " + message);
            // 更新聊天信息
        }
        public void broadcastMessage(SocketMode sender, String message) {
            // 遍历所有客户端，将消息发送到每个客户端
            for (SocketMode client : SocketMode.getClientList()) {
                if (client != sender) {
                    sendMessageToClient(client, message);  // 不广播给发送者自己
                }
            }
        }
        private void sendMessageToClient(SocketMode client, String message) {
            try {
                OutputStream outputStream = client.getSocket().getOutputStream();
                outputStream.write(message.getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // 添加客户端到客户端列表
        public void addClient(SocketMode socketMode) {
            SocketMode.getClientList().add(socketMode);
        }

        // 移除客户端
        public void removeClient(SocketMode socketMode) {
            SocketMode.removeClient(socketMode);
        }
    }
    public static class TalkServer {
        public static void main(String[] args) {

            Socket socket = new Socket();
            String clientName = "Client1";

            SocketMode socketMode = new SocketMode(socket, clientName);
            TalkServerReceiveHelper receiveHelper = new TalkServerReceiveHelper(socketMode);
            // 添加监听器
            TalkServerReceiveHelperListenerImpl listenerImpl = new TalkServerReceiveHelperListenerImpl();
            receiveHelper.addTalkServerReceiveHelperListener(listenerImpl);
            listenerImpl.addClient(socketMode);  // 将当前客户端添加到客户端列表

            // 启动服务器线程
            receiveHelper.start();
        }
    }
}
